<template>
  <div style="height: 100%; width: 100%; position: relative">
    <div class="pagetop">
      <div style="width: 100%">
        <table sborder="0" style="width: 100%; font-size: 12px; white-space: nowrap;">
          <tr>
            <td style="width: 60px; text-align: right;">原分单：</td>
            <td style="width: 210px;">
              <rm-ddl-common datatype="reqgroup" dataname="分单类别" v-model="groupsearch" :clearable="true"></rm-ddl-common>
            </td>
            <td style="width: 60px; text-align: right;">病人类型：</td>
            <td style="width: 210px;">
              <rm-ddl-common datatype="seccode" kindno="PT" dataname="病人类别选择" v-model="pattypesearch"></rm-ddl-common>
            </td>
            <td style="width: 60px; text-align: right;">标本：</td>
            <td style="width: 210px;">
              <rm-ddl-common v-model="specimensearch" datatype="specimen"
                irrelevant="specimenShowIrrelevant"></rm-ddl-common>
            </td>
            <td style="width: 60px; text-align: right;">科室：</td>
            <td style="width: 210px;">
              <rm-ddl-common v-model="deptsearch" datatype="dept" irrelevant="deptShowIrrelevant"></rm-ddl-common>
            </td>
            <td style="width: 60px; text-align: right;">合并后分单：</td>
            <td style="width: 210px;">
              <rm-ddl-common datatype="reqgroup" v-model="newgroupsearch" dataname="合并后分单类别"></rm-ddl-common>
            </td>
            <td></td>
          </tr>
        </table>

        <div class="operation-list">
          <el-button icon="el-icon-search" @click="InitPageData" type="primary"> 查询</el-button><el-button
            icon="el-icon-plus" @click="operatemdl(1)">新增</el-button><el-button icon="el-icon-delete"
            @click="operatemdl(3)">删除</el-button><el-button icon="el-icon-document" @click="saverecord">保存</el-button>
        </div>
      </div>
    </div>
    <div class="pagecenter">
      <div class="middle-center" style="height: 100%">
        <vxe-table show-overflow ref="xTable" height="auto" :loading="loading" :data.sync="list"
          :keyboard-config="keyConfig" show-header-overflow :edit-config="{
            trigger: 'click',
            mode: 'cell',
            showStatus: true,
            showIcon: false,
            activeMethod: cellactiveMethod,
          }" :header-cell-class-name="headerCellClassName" :row-class-name="rowClassName" highlight-current-row
          highlight-hover-row resizable border size="mini" @cell-dblclick="opendialog"
          @current-change="currentChangeEvent" :mouse-config="{ selected: true }" @edit-closed="Cell_Close">
          <vxe-table-column field="req_groupname" title="分单类别(双击开窗)" width="150" align="center" header-align="center">
          </vxe-table-column>
          <vxe-table-column field="pat_typename" title="病人类型(双击开窗)" width="120" align="center" header-align="center"
            :edit-render="{ name: 'input' }" :formatter="formatterFun">
          </vxe-table-column>
          <vxe-table-column field="specimen_name" title="标本类型(双击开窗)" width="120" align="center" header-align="center"
            :edit-render="{ name: 'input' }" :formatter="formatterFun">
          </vxe-table-column>
          <vxe-table-column field="req_deptname" title="科室(双击开窗)" width="150" align="left" header-align="center"
            :edit-render="{ name: 'input' }" :formatter="formatterFun">
          </vxe-table-column>
          <vxe-table-column field="ageyear1" title="年龄1(岁)>=" width="80" align="center" header-align="center"
            :edit-render="{ name: 'input' }" :formatter="formatterFun">
          </vxe-table-column>
          <vxe-table-column field="agestr1" title="年龄1显示(约)" width="90" align="center" header-align="center">
          </vxe-table-column>
          <vxe-table-column field="ageyear2" title="年龄2(岁)<=" width="80" align="center" header-align="center"
            :edit-render="{ name: 'input' }" :formatter="formatterFun">
          </vxe-table-column>
          <vxe-table-column field="agestr2" title="年龄2显示(约)" width="90" align="center" header-align="center">
          </vxe-table-column>
          <vxe-table-column field="newgroupname" title="合并后分单类别(双击开窗)" width="150" align="center" header-align="center">
          </vxe-table-column>
          <vxe-table-column field="seq" title="优先级" width="50" align="center" header-align="center"
            :edit-render="{ name: 'input' }">
          </vxe-table-column>
        </vxe-table>
      </div>
    </div>

    <el-dialog v-el-drag-dialog :append-to-body="true" :close-on-click-modal="false" title="请选择标本类型"
      :visible.sync="specimendialog">
      <rm-pop-common @change="specimenchange" @cancel="specimendialog = false" datatype="specimen"
        irrelevant="specimenShowIrrelevant"></rm-pop-common>
    </el-dialog>

    <el-dialog v-el-drag-dialog :append-to-body="true" :close-on-click-modal="false" title="请选择科室"
      :visible.sync="deptdialog">
      <rm-pop-common @change="deptchange" @cancel="deptdialog = false" datatype="dept"
        irrelevant="deptShowIrrelevant"></rm-pop-common>
    </el-dialog>

    <el-dialog v-el-drag-dialog :append-to-body="true" :close-on-click-modal="false" title="病人类别选择"
      :visible.sync="pattypedialog">
      <rm-pop-common datatype="seccode" kindno="PT" dataname="病人类别选择" @change="pattypechange"
        @cancel="pattypedialog = false"></rm-pop-common>
    </el-dialog>

    <el-dialog v-el-drag-dialog :append-to-body="true" :close-on-click-modal="false" title="分单类别"
      :visible.sync="reqgroupnodialog">
      <rm-pop-common datatype="reqgroup" dataname="分单类别" @change="reqgroupchange"
        @cancel="reqgroupnodialog = false"></rm-pop-common>
    </el-dialog>

    <el-dialog v-el-drag-dialog :append-to-body="true" :close-on-click-modal="false" title="合并后分单类别"
      :visible.sync="newreqgroupnodialog">
      <rm-pop-common datatype="reqgroup" dataname="合并后分单类别" @change="newreqgroupchange"
        @cancel="newreqgroupnodialog = false"></rm-pop-common>
    </el-dialog>

    <!--病人年龄-->
    <el-dialog v-el-drag-dialog :append-to-body="true" :close-on-click-modal="false" title="病人年龄" ref="dialogage"
      :visible.sync="ageshowdialog" width="450px">
      <table class="table1style">
        <tr>
          <td>
            <el-input v-model="age.agenum1" type="number" style="width:80px" @change="getAgestr" @focus="ageFocus($event)"
              ref="refagenum1"></el-input>
          </td>
          <td>
            <el-radio-group v-model="age.ageunit1">
              <el-radio :label="'Y'" @change="agenum1Change('Y')">岁</el-radio>
              <el-radio :label="'M'" @change="agenum1Change('M')">月</el-radio>
              <el-radio :label="'D'" @change="agenum1Change('D')">天</el-radio>
            </el-radio-group>
          </td>
        </tr>
      </table>
      <div style="color:rgb(68 170 246);margin:5px">
        返回年龄：{{ age.agemodel }}<br>
        可在前台病人年龄框中输入：{{ age.agestr }}返回相同结果
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click.native="$refs.dialogage.Confirm()">确 定</el-button>
        <el-button @click.native="$refs.dialogage.Cancel()">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script type="text/javascript">
import XEUtils from 'xe-utils';
export default {
  name: 'MNG245',
  data() {
    return {
      itemOptions: [],
      rptitemcode: '',
      rptitemname: '',
      specimenOptions: [],
      deptOptions: [],
      loading: false,
      Formdialog: false,
      okFirstLoading: false,
      specimendialog: false,
      deptdialog: false,
      pattypedialog: false,
      reqgroupnodialog: false,
      newreqgroupnodialog: false,
      rptitemsearchdialog: false,
      ageshowdialog: false,
      groupsearch: '',
      pattypesearch: '',
      specimensearch: '',
      deptsearch: '',
      newgroupsearch: '',
      dialogtitle: '',
      Trptunitid: '',
      tempindex: 0,
      actionindex: 0,
      tableData: [],
      WarnResultListdialog: false,
      TxtResultListdialog: false,
      dangerTableData: [],
      warnTableData: [],
      chkAsDanger: '1',
      chkAsWarn: '1',
      keyConfig: {
        isArrow: true,
        isDel: true,
        isTab: true,
        isEdit: true,
      },
      age: {
        agenum1: "",
        agenum2: "",
        ageunit1: "M",
        ageunit2: "D",
        agestr: "",
        agemodel: "",
      },

      disabled: false,
      perEditflag: false,
      Qrptunitid: '',
      Qrptunitname: '',
    };
  },
  watch: {},
  computed: {
    list() {
      let group = this.groupsearch;
      let pattype = this.pattypesearch;
      let specimen = this.specimensearch;
      let dept = this.deptsearch;
      let newgroup = this.newgroupsearch;
      let rest = this.tableData;
      rest = group ? rest.filter((item) => {
        return (
          item.req_groupid
            .toString()
            .toUpperCase()
            .indexOf(group.toString().toUpperCase()) > -1
        );
      }) : rest;
      rest = pattype ? rest.filter((item) => {
        return item.pat_typecode.toUpperCase().indexOf(pattype.toUpperCase()) > -1;
      }) : rest;
      rest = specimen ? rest.filter((item) => {
        return item.specimen_code.toUpperCase().indexOf(specimen.toUpperCase()) > -1;
      }) : rest;
      rest = dept ? rest.filter((item) => {
        return item.req_deptno.toUpperCase().indexOf(dept.toUpperCase()) > -1;
      }) : rest;
      rest = newgroup ? rest.filter((item) => {
        return (
          item.newgroupid
            .toString()
            .toUpperCase()
            .indexOf(newgroup.toString().toUpperCase()) > -1
        );
      }) : rest;
      return rest;
    },
  },
  created() {
    this.InitPageData(); //初始化主列表
  },
  mounted() { },
  updated() {
    // if (this.okFirstLoading) {
    //   let currentrow = (currentrow = this.$refs.xTable.getData(0));
    //   this.$nextTick(() => {
    //     if (currentrow) {
    //       this.okFirstLoading = false;
    //       this.$refs.xTable.setCurrentRow(currentrow);
    //       this.curselectrow = currentrow;
    //     }
    //   });
    // }
  },
  methods: {
    formatterFun({ column, cellValue }) {
      let fieldArr = ['specimen_name', 'deptname', 'diag_icd', 'physicyclename'];
      let fieldAge = ['ageyear1', 'ageyear2'];
      if (fieldArr.includes(column.property)) {
        if (cellValue == '' || cellValue == 'All' || cellValue == null) {
          return '';
        } else {
          return cellValue;
        }
      } else if (fieldAge.includes(column.property)) {
        if (cellValue == "-1") {
          return "";
        } else {
          return cellValue;
        }
      }
      else {
        return cellValue;
      }
    },
    specimenchange(code, name) {
      this.curselectrow.specimen_code = code;
      this.curselectrow.specimen_name = name;
      this.specimendialog = false;
    },
    deptchange(code, name) {
      this.curselectrow.req_deptno = code;
      this.curselectrow.req_deptname = name;
      this.deptdialog = false;
    },
    pattypechange(code, name) {
      this.curselectrow.pat_typecode = code;
      this.curselectrow.pat_typename = name;
      this.pattypedialog = false;
    },

    reqgroupchange(code, name) {
      this.curselectrow.req_groupid = code;
      this.curselectrow.req_groupname = name;
      this.reqgroupnodialog = false;
    },
    newreqgroupchange(code, name, val) {
      this.curselectrow.newgroupid = code;
      this.curselectrow.newgroupname = name;
      this.newreqgroupnodialog = false;
    },

    InitPageData() {
      this.loading = true;
      this.$tool
        .request({
          url: 'MNG/MNG2/MNG245',
          method: 'post',
          data: {
            action: 'query',
          },
        })
        .then((response) => {
          this.tableData = response.Data;
          this.loading = false;
          this.okFirstLoading = true;
        })
        .catch((e) => {
          this.loading = false;
          console.log('error', e);
        });
    },

    currentChangeEvent({ row, $rowIndex }) {
      this.tempindex = $rowIndex;
      this.actionindex = 2; //修改
      this.Trptunitid = row.rptunitid;
      this.curselectrow = row;
    },
    cellactiveMethod({ row, column, cellValue }) {
      let columnArr = [
        'physicyclename',
        'specimen_name',
        'deptname',
        'rptunitname',
        'rpt_itemname',
        'limit_rule',
      ];
      if (columnArr.includes(column.property)) {
        return false;
      } else {
        return true;
      }
    },
    rowClassName({ row, rowIndex }) {
      let isDirty = this.$refs.xTable.hasRowChange(row);
      if (isDirty) {
        return 'row-modify';
      }
      if (this.$refs.xTable.hasRowInsert(row)) return 'row-new';
    },
    opendialog({ row, column }) {
      if (column.property == 'req_deptname') {
        this.deptdialog = true;
      } else if (column.property == 'pat_typename') {
        this.pattypedialog = true;
      } else if (column.property == 'specimen_name') {
        this.specimendialog = true;
      } else if (column.property == 'req_groupname') {
        this.reqgroupnodialog = true;
      } else if (column.property == 'newgroupname') {
        this.newreqgroupnodialog = true;
      } else if (["ageyear1", "ageyear2"].includes(column.property)) {
        this.age.agenum1 = "";
        this.age.agenum2 = "";
        this.age.ageunit1 = "M";
        this.age.ageunit2 = "D";
        this.age.agestr = "";
        this.age.agemodel = "";
        setTimeout(() => {
          this.$refs.refagenum1.focus();
        }, 10);
        this.ageShowDialog(row, column);
      } else {
      }
    },
    headerCellClassName({ column, columnIndex }) {
      if (
        column.property == 'req_groupname' ||
        column.property == 'req_groupid' ||
        column.property == 'newgroupid' ||
        column.property == 'newgroupname'
      ) {
        return 'col-blue';
      }
    },
    operatemdl(k) {
      if (k == 1) {
        //新增
        let xTable1date = this.$refs.xTable.tableData;
        let len = (xTable1date.length + 1) * 10;
        this.$refs.xTable
          .insert({
            mergeid: '',
            req_groupid: '',
            req_groupname: '',
            pat_typecode: 'All',
            pat_typename: '',
            specimen_code: 'All',
            specimen_name: '',
            req_deptno: 'All',
            req_deptname: '',
            ageyear1: "-1",
            ageyear2: "-1",
            seq: len,
            newgroupid: '',
            newgroupname: '',
          })
          .then(({ row }) => {
            this.$nextTick(() => {
              this.curselectrow = row;
              this.$refs.xTable.setCurrentRow(row);
              this.$refs.xTable.setActiveRow(row, 'rpt_itemname');
            });
          });
        this.actionindex = 1; //新增
      } else if (k == 2) {
        //修改
        this.actionindex = 2; //新增
        this.perEditflag = true;
      } else {
        this.actionindex = 3;
        //删除
        try {
          var delrow = this.$refs.xTable.getCurrentRow();
          if (delrow) {
            this.$confirm('确定要删除这条数据吗？', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            })
              .then(() => {
                var alld = this.$refs.xTable.tableData;
                var rowindex = alld.indexOf(delrow);
                this.$refs.xTable.remove(delrow);
                let havedata = this.$refs.xTable.tableData;
                if (havedata.length > 0) {
                  if (rowindex >= havedata.length) rowindex = havedata.length - 1;
                  let selectrow = havedata[rowindex];
                  this.$refs.xTable.setCurrentRow(selectrow);
                }
              })
              .catch(() => { });
          }
        } catch (e) {
          console.log('error', e);
        }
      }
    },
    FunScrollY() {
      this.$nextTick(() => {
        var alldataLen = this.$refs.xTable.tableData.length;
        let L = this.$refs.xTable.getTableData().fullData[alldataLen - 1];
        this.$refs.xTable.scrollToRow(L);
      });
    },
    saverecord() {
      let xTable1date = this.$refs.xTable.tableData;
      xTable1date.sort((a, b) => {
        return Number(a.seq) - Number(b.seq);
      });

      let data = this.$refs.xTable.getRecordset();
      let filterdata = xTable1date.filter((item) => (item.req_groupid == '' || item.req_groupid == null) ||
        item.newgroupid == ''
      );
      if (filterdata.length > 0) {
        this.$message.warning('保存的数据分单类别和合并后分单类别不能为空，请开窗选择！');
        return false;
      }
      //序号重整
      this.$tool
        .request({
          url: 'MNG/MNG2/MNG245',
          method: 'post',
          data: {
            action: 'save',
            urec: data,
          },
        })
        .then((response) => {
          if (response.errcode == '1') {
            this.$message({
              message: '操作成功！',
              type: 'success',
            });
            this.InitPageData();
          } else {
            this.$alert('保存失败！' + response.errmsg);
          }
        });
    },
    Cell_Close({ row, column }, $event) {
      if (column.property == "ageyear1") {
        if (!!row.ageyear1) {
          this.GetPatBirthAge(row.ageyear1)
            .then((res) => {
              if (res.str && res.str1 != "") {
                row.ageyear1 = res.str;
                row.agestr1 = res.str1;
              } else {
                if (res.str != "-1") {
                  row.ageyear1 = "-1";
                  row.agestr1 = "";
                } else {
                  row.agestr1 = "";
                }
              }
            })
            .catch((e) => {
            });
        } else {
          row.ageyear1 = "-1";
          row.agestr1 = "";
        }
      } else if (column.property == "ageyear2") {
        if (!!row.ageyear2) {
          this.GetPatBirthAge(row.ageyear2)
            .then((res) => {
              if (res.str && res.str1 != "") {
                row.ageyear2 = res.str;
                row.agestr2 = res.str1;
              } else {
                if (res.str != "-1") {
                  row.ageyear2 = "-1";
                  row.agestr2 = "";
                } else {
                  row.agestr2 = "";
                }
              }
            })
            .catch((e) => {
            });
        } else {
          row.ageyear2 = "-1";
          row.agestr2 = "";
        }
      }
    },
    ageShowDialog(row, column) {
      this.$refs.dialogage
        .ShowDialog()
        .then(() => {
          if (this.age.agenum1 == "") {
            this.ageShowDialog(row, column);
            this.$alert("请输入一级年龄！", "提示");
            return false;
          }

          if (column.property == "ageyear1") {
            if (!!this.age.agenum1 && Number(this.age.agenum1) != -1) {
              this.getAgestr();
              this.GetPatBirthAge(this.age.agestr)
                .then((res) => {
                  row.ageyear1 = res.str;
                  row.agestr1 = res.str1;
                })
                .catch((e) => {
                  //row.ageyear1 = "-1";
                });
            } else {
              //row.ageyear1 = "-1";
            }
          } else if (column.property == "ageyear2") {
            if (!!this.age.agenum1 && Number(this.age.agenum1) != -1) {
              this.getAgestr();
              this.GetPatBirthAge(this.age.agestr)
                .then((res) => {
                  row.ageyear2 = res.str;
                  row.agestr2 = res.str1;
                })
                .catch((e) => {
                  // row.ageyear2 = "-1";
                });
            } else {
              //row.ageyear2 = "-1";
            }
          }
        })
        .catch(() => {
          console.log("catch");
        });
    },
    getAgestr() {
      if (this.age.ageunit1 != this.age.ageunit2) {
        if (this.age.agenum1 != "") {
          this.age.agestr = this.age.agenum1 + this.age.ageunit1;
        }
        if (this.age.agenum2 != "") {
          this.age.agestr += this.age.agenum2 + this.age.ageunit2;
        }
      } else {
        if (this.age.agenum1 != "") this.age.agestr = this.age.agenum1 + this.age.ageunit1;
        this.age.agenum2 = "";
      }
      this.age.agestr = this.age.agestr.toLowerCase();
      if (this.age.agestr != "") this.age.agemodel = this.age.agestr.toLowerCase().replace("y", "岁").replace("m", "月").replace("d", "天").replace("h", "小时").replace("f", "分钟");
    },
    GetPatBirthAge(agestr) {
      return this.$tool.request({
        url: "ucent/liscomm",
        method: "post",
        data: {
          action: "GetPatBirthAge",
          agestr: agestr,
        },
      });
    },
    //年龄相关
    ageFocus(event) {
      event.currentTarget.select();
    },
    agenum1Change(flag) {
      switch (flag) {
        case "Y":
          this.age.ageunit2 = "M";
          break;
        case "M":
          this.age.ageunit2 = "D";
          break;
        case "D":
          this.age.ageunit2 = "H";
          break;
        case "H":
          this.age.ageunit2 = "F";
          break;
        default:
          this.age.ageunit2 = "F";
      }
      this.getAgestr();
    },
  },
}
</script>

<style scoped>
.pagetop {
  left: 0;
  right: 0;
  display: -webkit-box;
  -webkit-box-pack: center;
  -webkit-box-align: center;
  border: solid 1px #ccc;
  position: absolute;
  z-index: 99;
  height: 80px;
  overflow-x: auto;
  overflow-x: overlay;
}

.pagecenter {
  position: absolute;
  top: 85px;
  bottom: 0px;
  overflow: auto;
  width: 100%;
  left: 0px;
}

.middle-center {
  position: absolute;
  height: 100%;
  left: 0px;
  right: 0px;
  overflow: auto;
}

.table1style tr td {
  padding: 0px 2px 0px 5px;
}

.operation-list {
  float: right;
  margin-top: 10px;
  margin-right: 5px;
  margin-bottom: 5px;
}

::deep .middle-center tr.vxe-body--row.row-modify {
  color: blue !important;
}

::deep .middle-center .vxe-header--column.col-blue {
  background-color: #2db7f5;
  color: #fff;
}

::deep .middle-center tr td div .el-input__inner {
  border: 1px solid rgba(255, 254, 254, 0) !important;
  background-color: rgba(255, 254, 254, 0) !important;
}
</style>
